<?php

/**
 * 后台文章logic操作
 * @author  xiaobai
 * @date    2019-03-27
 */

namespace app\panel\logic;

use app\common\model\Common;
use app\common\model\TagData;
use app\common\logic\Search;

class News extends Common
{
    /**
     * 整理搜索的where条件
     * @param array $formParams 搜索表格参数
     * @return array
     */
    public function searchWhere($formParams = array())
    {
        $count_where = array();
        $where       = array();
        $params      = array();

        $formParams['column_id'] = !empty($formParams['column_id']) ? $formParams['column_id'] : 0;
        if (!empty($formParams['column_id'])) {
            $where[]             = ['a.column_id', '=', $formParams['column_id']];
            $count_where[]       = ['column_id', '=', $formParams['column_id']];
            $params['column_id'] = $formParams['column_id'];
        }
        if (!empty($formParams['stat_time']) && !empty($formParams['end_time']) && strtotime($formParams['stat_time']) <= strtotime($formParams['end_time'])) {
            $where[]             = ['a.create_time', '>=', $formParams['stat_time'].' 00:00:00'];
            $where[]             = ['a.create_time', '<', $formParams['stat_time'].' 23:59:59'];
            $count_where[]       = ['create_time', '>=', $formParams['stat_time'].' 00:00:00'];
            $count_where[]       = ['create_time', '<', $formParams['stat_time'].' 23:59:59'];
            $params['stat_time'] = $formParams['stat_time'];
            $params['end_time']  = $formParams['end_time'];
        }
        $formParams['title'] = isset($formParams['title']) ? trim($formParams['title']) : '';
        if (isset($formParams['title']) && $formParams['title'] != '') {
            $where[]         = ['a.title', 'like', '%'.$formParams['title'].'%'];
            $count_where[]   = ['title', 'like', '%'.$formParams['title'].'%'];
            $params['title'] = $formParams['title'];
        }
        $formParams['is_top'] = isset($formParams['is_top']) ? $formParams['is_top'] : '';
        if (isset($formParams['is_top']) && $formParams['is_top'] != '') {
            $where[]          = ['a.is_top', '=', $formParams['is_top']];
            $count_where[]    = ['is_top', '=', $formParams['is_top']];
            $params['is_top'] = $formParams['is_top'];
        }

        return array('where'=>$where, 'count_where'=>$count_where, 'params'=>$params, 'formParams'=>$formParams);
    }

    /**
     * 保存文章处理
     * @param array $data   文章数据
     * @param int $id       编辑时文章id
     * @return array
     */
    public function saveNews($data = array(), $id = 0)
    {
        $position_ids = !empty($data['position_ids']) ? implode(',', $data['position_ids']) : '';
        $tags_str     = '';
        // 验证tag标签
        if (!empty($data['tags'])) {
            $check_res = model('common/Tag', 'logic')->checkTags($data['tags']);
            if ($check_res['code'] == 1) {
                return $this->result(1, $check_res['msg']);
            }
            $tags_str = $data['tags'];
        }
        unset($data['position_ids']);
        unset($data['tags']);

        // 非置顶时间段处理
        if ($data['is_top'] != 2) {
            $data['top_start_time'] = '1900-01-01 00:00:00';
            $data['top_end_time']   = '1900-01-01 00:00:00';
        }
        $data['admin_id']    = get_admin_id();
        $data['update_time'] = date('Y-m-d H:i:s');

        $this->startTrans();     // 开启事物

        // 保存文章内容
        // 处理tag标签重复信息
        if (!empty($tags_str)) {
            $tags     = explode(',', $tags_str);
            $tags     = array_unique($tags);     // 去重操作
            $tags_str = implode(',', $tags);
        }

        // 存在id值时更新数据
        if (!empty($id)) {
            unset($data['id']);
            $res = $this->save($data, ['id'=>$id]);
        } else {
            $res = $this->save($data);
        }
        if ($res === false) {
            $this->rollback();
            return $this->result(1, $this->getError());
        }

        $data['id'] = (!empty($id)) ? $id : $this->id;
        // 处理推荐位信息
        $ret = model('common/PositionData')->setPositionData($data, $position_ids);
        if ($ret['code'] == 0) {
            $this->rollback();
            return $this->result(1, $ret['msg ']);
        }

        // 处理tag标签信息
        if (!empty($tags_str)) {
            $tags    = explode(',', $tags_str);
            $tags    = array_unique($tags);     // 去重操作
            $tag_ids = model('common/Tag')->saveData($tags);
            if (count($tag_ids) != count($tags)) {
                $this->rollback();
                return $this->result(1, 'tag标签处理超时，请重新提交');
            }
        }
        // 处理tag标签对应文章集信息
        if (!empty($tag_ids)) {
            $where   = array('data_id'=>$data['id'], 'type'=>TagData::TYPE_NEWS);
            $tagData = new TagData();
            $tag_del = $tagData->where($where)->delete();
            if ($tag_del === false) {
                $this->rollback();
                return $this->result(1, 'tag标签处理失败，请重新提交');
            }

            $tag_data = array();
            foreach ($tag_ids as $k=>$v) {
                $tag_data[$k]['tag_id']  = $v;
                $tag_data[$k]['data_id'] = $data['id'];
                $tag_data[$k]['type']    = TagData::TYPE_NEWS;
            }
            $tag_res = $tagData->saveAll($tag_data);
            if ($tag_res === false) {
                $this->rollback();
                return $this->result(1, 'tag标签处理失败，请重新提交。');
            }
            @$tagData->delGetTagDataCache($data['id'], TagData::TYPE_NEWS);
        }

        // 同步迅搜索引库
        $xun_search_no = !empty(env('xun_search_no')) ? env('xun_search_no') : 0;
        if ($xun_search_no <= 0) {
            $is_up      = !empty($id) ? $id : 0;
            $xun_search = new Search();
            @$xun_search->setNewsIndex($data, $is_up);
        }

        $this->commit();
        return $this->result(0);
    }

}
